<template>
  <div :class="className" :style="{width:width,height:height}"></div>
</template>

<script>
import chartResize from '../mixins/chartsResize'
import { getMileStatistics } from '../../api/statics/index'
const echarts = require('echarts')

export default {
  mixins: [chartResize],
  props: {
    className: {
      type: String,
      default: 'pie'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data () {
    return {
      // Echarts实例
      chart: null
    }
  },
  watch: {
    /* 如果图表数据是后台获取的，监听父组件中的数据变化，重新触发Echarts */
    chartData: {
      deep: true,
      handler (val) {
        this.setOptions(val)
      }
    }
  },
  mounted () {
    this.getData()
    /* 图表初始化 */
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    /* 释放图表实例 */
    this.chart.dispose()
    /* dispose 会释放内部占用的一些资源和事件绑定，但是解除实例的引用我们是做不到的，所以需要重新赋值为null */
    this.chart = null
  },
  methods: {
    initChart () {
      this.chart = echarts.init(this.$el)
      this.setOptions()
    },
    setOptions () {
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          textStyle: {
            color: 'inherit',
            fontSize: '8'
          },
          data: ['0.0-1.0', '1.0-2.0', '2.0-3.0', '3.0-4.0', '4.0-']
        },
        series: [
          {
            name: '里程统计',
            type: 'pie',
            radius: [20, 100],
            center: ['35%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 10,
              borderJoin: 'round'
            },
            left: 50,
            fontSize: '8',
            emphasis: {
              show: false,
              position: 'center'
            },
            labelLine: {
              show: true
            },
            label: {
              color: 'inherit'
            },
            data: []
          }
        ]
      })
    },
    getData () {
      getMileStatistics()
        .then((res) => {
          console.log(res.data.data)
          var MileArray = res.data.data
          const newData = []
          let obj = {}
          MileArray.map(function (item) {
            obj = item
            // 替换键，替换成name和value
            obj.value = item.mileageCount
            obj.name = item.range
            delete obj.range
            delete obj.mileageCount
            newData.push(obj)
          })
          this.chart.setOption({
            series: [{
              data: newData
            }]
          })
          console.log(newData)
        })
    }
  }
}
</script>
